package com.devops.admin.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @ClassName JSONTypeHandlerPg
 * @Description TODO
 * @Author heyabo
 * @Date 2022/8/15 09:29
 * @Version 1.0
 **/
@MappedJdbcTypes(JdbcType.OTHER)
public class JSONTypeHandlerPg <T extends Object> extends BaseTypeHandler<T> {

    private static final PGobject jsonObject = new PGobject();
    private final Class<T> clazz;

    public JSONTypeHandlerPg(Class<T> clazz) {
        if (clazz == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.clazz = clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        PGobject jsonObject = new PGobject();
        jsonObject.setType("jsonb");
        jsonObject.setValue(this.toJson(parameter));
        ps.setObject(i, jsonObject);
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        PGobject pgObject = (PGobject) rs.getObject(columnName);
        return pgObject == null ? null : this.toObject(pgObject.getValue(), clazz);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        PGobject pgObject = (PGobject) rs.getObject(columnIndex);
        return pgObject == null ? null : this.toObject(pgObject.getValue(), clazz);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        PGobject pgObject = (PGobject) cs.getObject(columnIndex);
        return pgObject == null ? null : this.toObject(pgObject.getValue(), clazz);
    }

    private String toJson(T object) {
        try {
            return JSON.toJSONString(object, SerializerFeature.WriteNullListAsEmpty);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private T toObject(String content, Class<?> clazz) {
        if (content != null && !content.isEmpty()) {
            try {
                return (T) JSON.parseObject(content, clazz);
            } catch (Exception e) {
                // 记录错误日志
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

}
